<!DOCTYPE html >
<html lang="zh">
<head>
    <meta charset= "UTF-8" >
    <title>WebSocket测试</title >
    <link rel="icon" href="img/dgs.jpg" type="image/jpg" >
    <link rel="stylesheet" href="./layui/css/layui.css">
</head >
<body>
<div>
    <div id="Text1Dv">
        <button id="Open" onclick="OpenSocket()">开启Socket</button>
        <button id="Close" onclick="CloseSocket()">关闭Socket</button>
    </div>
    <input id= "start" >
    <input id= "message" >
    <iframe id= "my_iframe" style="display:none"></iframe >
</div>


<script src="https://cdn.jsdelivr.net/npm/jquery" charset="utf-8"></script>
<script src="https://www.layuicdn.com/layui/layui.js" charset="utf-8"></script>
<script type= "application/javascript" >
    var socket,userId=10 ;
    if ( typeof( WebSocket) == "undefined" ) {
        console.log ( " 您的浏览器不支持 WebSocket" );
    }
    else {
        console.log ( " 您的浏览器支持 WebSocket" );

        function OpenSocket() {
                socket = new WebSocket ( "ws://localhost:8848/websocket/"+userId);
                // 打开事件
            socket.onopen = function () {
                console.log ( "Socket 已打开 " );
                $( "#start" ). val ( "Socket 已打开 " )
            };

            // 获得消息事件
            socket.onmessage = function (msg) {
                let confirm1=layer.confirm('发现新数据，是否打印显示出', {
                        title:'新消息确认',btn: ['确定','忽略'],resize:false
                    }
                    ,function () {
                        layer.msg(msg.data)
                        socket.on('open',function(){
                            socket.send('返回后台成功')
                        })
                        layer.close(confirm1)
                    }
                    ,function () {
                        layer.close(confirm1)
                    })
// 发现消息进入 开始处理前端触发逻辑
            };

// 发生了错误事件
            socket .onerror = function () {
                alert ( "Socket 发生了错误 " );
// 此时可以尝试刷新页面
            };
            }

          /* function SendInformation() {
            let newDate='返回后台成功'
                socket.send("发送信息到后台"+"ws://localhost:8848/websocket/"+newDate);
            }*/

        function CloseSocket(){
            // 关闭事件
           socket.close();
            socket.onclose = function () {
                console.log ( "Socket 已关闭 " );
                $("#start").val ("Socket已关闭")
            };
        }
}
</script>

</body >
</html >
